<?php
/**
 * 手机接口
 *@apiDefine  backpack
 */
namespace App\Http\Controllers\Wap;
use App\Http\Controllers\Controller;
use App\Http\Requests\StoreRequest;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

Class IndexController extends Controller{


    /**
	*@api {get} wap/index 获取首页列表
	*@apiName backpack
    *@apiGroup backpack
	*@apiSuccess {String}  menu 栏目
	*@apiSuccess {String} title 标题
	*@apiSuccess {String}  id 内容id
	*@apiSuccess {String} img 	缩略图
	*@apiSuccess {String}  sorttile 小标题
	*@apiSuccess {String}  highcommission 高佣金线路
	*@apiSuccess {String}  sellwell 热销线路
	*@apiSuccess {String}  newest 最新线路
     *@apiSuccessExample Success-Response:
         * {
         * code:"200"
         * }	
	*/
    public function  index(){
        //获取栏目
        $menu = DB::table('tour_menu')->select('menu_id','name','menu_img')->limit('8')->get();
        //最新线路
        $newest = DB::table('content')->select('id','title','img','commission','sorttile','price')->limit('3')->where('newest','on')->get();
        $highcommission = DB::table('content')->select('id','title','img','commission','sorttile','price')->limit('3')->where('highcommission','on')->get();
        $sellwell = DB::table('content')->select('id','title','img','commission','sorttile','price')->limit('3')->where('sellwell','on')->get();
        $arr=array();
        $arr['code']='200';
         $menu_arr = json_decode(json_encode($menu),true);

        foreach ($menu_arr as $k=>&$v){
                $menu_arr[$k]['img'] =  'https://www.hellofd.vip'.$v['menu_img'];
        }

        //$arr['menu']['img']= $menu['menu_img'];
        $arr['menu'] = $menu_arr;
        $arr['highcommission'] = $highcommission;
        $arr['sellwell'] = $sellwell;
		$arr['newest'] = $newest;
        if(!empty($arr)){
            return json_encode($arr);
        }else{
            $arr['code']= '101';
            $arr['msg']= '没有数据';
            return json_encode($arr);
        }
}
/**
 * 内容
  *@api {get} wap/content 获取内容详细接口
  *@apiName backpack-content
  *@apiGroup backpack
  * @apiParam {string} id 内容id
  *@apiSuccess {String}  menu 栏目
  *@apiSuccess {String} title 标题
  *@apiSuccess {String} img 	缩略图
 *@apiSuccess {String}  sorttile 小标题
  *@apiSuccess {String}  price 售价
  *@apiSuccess {String}  price 佣金
  *@apiSuccess {String}  setime 起始时间
  *@apiSuccess {String}  mobile 手机号
	*@apiSuccessExample Success-Response:
     * {
       * code:"200"
    * }
 */
public function content(StoreRequest $request){
    $data = $request->all();
    $id =  $data['id'];
    $content = DB::table('content')->leftJoin('admin_users','admin_users.id','=','content.user_id')->select('title','content','price','img','commission','sorttile','setime','admin_users.mobile')->where('content.id',$id)->first();

    if(!$content){
        return json_encode(['code'=>'101','msg'=>'数据不存在']);
    }else{
        return json_encode(['code'=>'200','data'=>$content]);
    }
}
/**
 * 列表
 * 高佣金线路， 最新线路 ，热销线路 ，状态为on
  *@api {get} wap/lists 获取列表接口
  *@apiName backpack-lists
  *@apiGroup backpack
  *@apiParam {string} menu_id 栏目id可选
  *@apiParam {string} title 标题可选
   *@apiParam {string} highcommission 高佣金线路可选 传on
   *@apiParam {string} newest  最新线路可选 传on
   *@apiParam {string} sellwell  热销线路可选 传on
   *@apiParam {string} sellwell  热销线路可选 传on
    *@apiParam {string} page  页数 传1,2,3 
   *@apiParam {string} title 标题可选
  *@apiSuccess {String}  menu 栏目
  *@apiSuccess {String} title 标题
  *@apiSuccess {String} img 	缩略图
 *@apiSuccess {String}  sorttile 小标题
	*@apiSuccessExample Success-Response:
   * {
       * code:"200"
    * }
 */
public function lists(StoreRequest $request){
    $data = $request->all();
    $map= array();
    !empty($data['title']) ? $map['title'] = $data[ 'title'] : '';
    !empty($data['menu_id']) ? $map['menu_id'] = $data[ 'menu_id'] : '';
    !empty($data['highcommission'])?$map['highcommission'] = $data['highcommission'] : '';
    !empty($data['newest'])?$map['newest'] = $data['newest'] : '';
    !empty($data['sellwell'])?$map['sellwell'] = $data['sellwell'] : '';
    $count = DB::table('content')->where($map)->count();
    $list = DB::table('content')->where($map)->paginate('15');
    if(!$list){
        return json_encode(['code'=>'101','msg'=>'数据不存在']);
    }
    return json_encode(['code'=>'200','data'=>$list]);
  //  echo $count;

}

//旅行社注册
/**
*
 *@api {post} wap/register 注册接口
  *@apiName backpack-register
  *@apiGroup backpack
  *@apiParam {string} username 姓名
  *@apiParam {string} pwd 密码
  *@apiParam {string} mobile 手机号
  *@apiParam {string} agency_name 旅行社名字
   *@apiParam {string} agency_img 旅行社缩略图
   *@apiParam {string} qrcode 旅行社二维码
  	*@apiSuccessExample Success-Response:
   * {
       * code:"200"
    * } 
*
*/

public function register(StoreRequest $request){
    $data = $request->all();
    $map= array();
    $map['username'] = $data['username'];
    $map['password'] = bcrypt($data['pwd']);

    $map['mobile'] = $data['mobile'];
    $map['created_at'] = date('Y-m-d H:i:s',time());
    $result = DB::table('admin_users')->where(['username'=>$map['username'],'mobile'=>$map['mobile']])->get();
    if(empty($result)){
        return json_encode(['code'=>'101','msg'=>'已存在该用户']);
    }
    $id = DB::table('admin_users')->insertGetId($map); //获取自增userid
    $map2['agency_name'] = $data['agency_name'];
    $map2['user_id'] = $id;
    $map2['addtime'] = date('Y-m-d H:i:s',time());
    !empty($data['agency_img'])?$map2['agency_img'] = $data['agency_img'] : '';
    !empty($data['qrcode'])?$map2['qrcode'] = $data['qrcode'] : '';
    DB::table('agency')->insert($map2);
    //普通管理员 role_id 为2
    $model = DB::table('admin_role_user')->insert(['user_id'=>$id,'role_id'=>'2']);
    if($model){
        return json_encode(['code'=>'200','msg'=>'添加成功']);
    }else{
        return json_encode(['code'=>'101','msg'=>'添加失败']);
    }
}
//旅行社上传
/**
*
 *@api {post} wap/upload 上传接口
  *@apiName backpack-upload
  *@apiGroup backpack
  *@apiParam {string} img 上传文件名
  	*@apiSuccessExample Success-Response:
   * {
       * code:"200"
    * } 
*
*/
    public function upload(StoreRequest $request){
        $file = $request->file('img');
        // 此时 $this->upload如果成功就返回文件名不成功返回false
        $fileName = $this->uploadfile($file);
        if ($fileName){
            return json_encode(['code'=>'200','imgurl'=>$fileName,'msg'=>'上传成功']);
            // return $fileName;
        }
        return json_encode(['code'=>'101','msg'=>'上传失败']);
    }
    public function uploadfile($file, $disk='public') {
        // 1.是否上传成功


        // 2.是否符合文件类型 getClientOriginalExtension 获得文件后缀名
        $fileExtension = $file->getClientOriginalExtension();
        if(! in_array($fileExtension, ['png', 'jpg', 'gif'])) {
            return false;
        }

        // 3.判断大小是否符合 2M
        $tmpFile = $file->getRealPath();
        if (filesize($tmpFile) >= 2048000) {
            return false;
        }

        // 4.是否是通过http请求表单提交的文件
        if (! is_uploaded_file($tmpFile)) {
            return false;
        }

        // 5.每天一个文件夹,分开存储, 生成一个随机文件名
        $fileName =date('Ymd').'/'.md5(time()) .mt_rand(0,9999).'.'. $fileExtension;
        if (Storage::disk('uploads')->put($fileName, file_get_contents($tmpFile)) ){
            return($fileName);
            //return Storage::url($fileName);
        }
    }

    public function generate(){
        $phpqrcode = new \QRcode();

        $value = 'http://www.baidu.com'; //二维码内容

        $errorCorrectionLevel = 'L';//容错级别

        $matrixPointSize = 6;//生成图片大小

//生成二维码图片

        $phpqrcode::png($value, 'qrcode.png', $errorCorrectionLevel, $matrixPointSize, 2);

        $logo = 'logo.jpg';//准备好的logo图片  需要加入到二维码中的logo

        $QR = 'qrcode.png';//已经生成的原始二维码图



        if ($logo !== FALSE) {

            $QR = imagecreatefromstring(file_get_contents($QR));

            $logo = imagecreatefromstring(file_get_contents($logo));

            $QR_width = imagesx($QR);//二维码图片宽度

            $QR_height = imagesy($QR);//二维码图片高度

            $logo_width = imagesx($logo);//logo图片宽度

            $logo_height = imagesy($logo);//logo图片高度

            $logo_qr_width = $QR_width / 5;

            $scale = $logo_width/$logo_qr_width;

            $logo_qr_height = $logo_height/$scale;

            $from_width = ($QR_width - $logo_qr_width) / 2;

//重新组合图片并调整大小

            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,

                $logo_qr_height, $logo_width, $logo_height);

        }

//输出图片

        imagepng($QR, 'helloweba.png');

        echo '<img src="/helloweba.png">';

    }
    public function getImg(StoreRequest $request){
        $data = $request->all();
        $id =  $data['id'];
        $content = DB::table('content')->leftJoin('admin_users','admin_users.id','=','content.user_id')->select('title','content','price','img','commission','sorttile','setime','admin_users.mobile')->where('content.id',$id)->get();
        $content = json_decode(json_encode($content),true);
       $title = $content['0']['title'];
        $price = $content['0']['price'];
        $img = $content['0']['img'];
        $commission = $content['0']['commission'];
        $setime = $content['0']['setime'];
        $mobile = $content['0']['mobile'];
       // die();
        $config = array(
            'text'=>array(
                array(
                    'text'=>$title,
                    'left'=>60,
                    'top'=>240,
                    'fontPath'=>'simhei.ttf',     //字体文件
                    'fontSize'=>18,             //字号
                    'fontColor'=>'0,0,0',       //字体颜色
                    'angle'=>0,
                ),
                array(
                    'text'=>'售价：'.$price,
                    'left'=>60,
                    'top'=>270,
                    'fontPath'=>'simhei.ttf',     //字体文件
                    'fontSize'=>18,             //字号
                    'fontColor'=>'0,0,0',       //字体颜色
                    'angle'=>0,
                ),
                array(
                    'text'=>'佣金：'.$commission,
                    'left'=>60,
                    'top'=>300,
                    'fontPath'=>'simhei.ttf',     //字体文件
                    'fontSize'=>18,             //字号
                    'fontColor'=>'0,0,0',       //字体颜色
                    'angle'=>0,
                ),
                array(
                    'text'=>'时间：'.$setime,
                    'left'=>60,
                    'top'=>330,
                    'fontPath'=>'simhei.ttf',     //字体文件
                    'fontSize'=>18,             //字号
                    'fontColor'=>'0,0,0',       //字体颜色
                    'angle'=>0,
                ),
                array(
                    'text'=>'联系电话：'.$mobile,
                    'left'=>60,
                    'top'=>360,
                    'fontPath'=>'simhei.ttf',     //字体文件
                    'fontSize'=>18,             //字号
                    'fontColor'=>'0,0,0',       //字体颜色
                    'angle'=>0,
                ),
            ),
            'image'=>array(
                array(
                    'url'=>'.'.$img,       //图片资源路径
                    'left'=>80,
                    'top'=>50,
                    'stream'=>0,             //图片资源是否是字符串图像流
                    'right'=>0,
                    'bottom'=>0,
                    'width'=>150,
                    'height'=>150,
                    'opacity'=>100
                ),
     /*           array(
                    'url'=>'https://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83eofD96opK97RXwM179G9IJytIgqXod8jH9icFf6Cia6sJ0fxeILLMLf0dVviaF3SnibxtrFaVO3c8Ria2w/0',
                    'left'=>120,
                    'top'=>70,
                    'right'=>0,
                    'stream'=>0,
                    'bottom'=>0,
                    'width'=>55,
                    'height'=>55,
                    'opacity'=>100
                ),*/
            ),
            'background'=>'bk.jpg',
        );
        $filename = 't'.time().'.jpg';
//echo createPoster($config,$filename);
       // echo createPoster($config);
      //点击下载图片
        $this->createPoster($config,$filename);
        header("Cache-control: private");
        header("Content-type: image/jpeg'");
        header("Content-Length:".filesize('uploads/poster/'.$filename));
        header("Content-disposition:attachment;filename=".urldecode($filename).";");

        readfile('uploads/poster/'.$filename);
     //   echo $this->createPoster($config,$filename);
    }
    public function createPoster($config=array(),$filename=''){
        if(empty($filename)) header("content-type: img/png");
        $imageDefault = array(
            'left'=>0,
            'top'=>0,
            'right'=>0,
            'bottom'=>0,
            'width'=>100,
            'height'=>100,
            'opacity'=>100
        );
        $textDefault = array(
            'text'=>'',
            'left'=>0,
            'top'=>0,
            'fontSize'=>32,       //字号
            'fontColor'=>'255,255,255', //字体颜色
            'angle'=>0,
        );
        $background = $config['background'];//海报最底层得背景
        $backgroundInfo = getimagesize($background);
        $backgroundFun = 'imagecreatefrom'.image_type_to_extension($backgroundInfo[2], false);
        $background = $backgroundFun($background);
        $backgroundWidth = imagesx($background);  //背景宽度
        $backgroundHeight = imagesy($background);  //背景高度
        $imageRes = imageCreatetruecolor($backgroundWidth,$backgroundHeight);
        $color = imagecolorallocate($imageRes, 0, 0, 0);
        imagefill($imageRes, 0, 0, $color);
        // imageColorTransparent($imageRes, $color);  //颜色透明
        imagecopyresampled($imageRes,$background,0,0,0,0,imagesx($background),imagesy($background),imagesx($background),imagesy($background));
        //处理了图片
        if(!empty($config['image'])){
            foreach ($config['image'] as $key => $val) {
                $val = array_merge($imageDefault,$val);
                $info = getimagesize($val['url']);
                $function = 'imagecreatefrom'.image_type_to_extension($info[2], false);
                if($val['stream']){   //如果传的是字符串图像流
                    $info = getimagesizefromstring($val['url']);
                    $function = 'imagecreatefromstring';
                }
                $res = $function($val['url']);
                $resWidth = $info[0];
                $resHeight = $info[1];
                //建立画板 ，缩放图片至指定尺寸
                $canvas=imagecreatetruecolor($val['width'], $val['height']);
                imagefill($canvas, 0, 0, $color);
                //关键函数，参数（目标资源，源，目标资源的开始坐标x,y, 源资源的开始坐标x,y,目标资源的宽高w,h,源资源的宽高w,h）
                imagecopyresampled($canvas, $res, 0, 0, 0, 0, $val['width'], $val['height'],$resWidth,$resHeight);
                $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']) - $val['width']:$val['left'];
                $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']) - $val['height']:$val['top'];
                //放置图像
                imagecopymerge($imageRes,$canvas, $val['left'],$val['top'],$val['right'],$val['bottom'],$val['width'],$val['height'],$val['opacity']);//左，上，右，下，宽度，高度，透明度
            }
        }
        //处理文字
        if(!empty($config['text'])){
            foreach ($config['text'] as $key => $val) {
                $val = array_merge($textDefault,$val);
                list($R,$G,$B) = explode(',', $val['fontColor']);
                $fontColor = imagecolorallocate($imageRes, $R, $G, $B);
                $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']):$val['left'];
                $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']):$val['top'];
                imagettftext($imageRes,$val['fontSize'],$val['angle'],$val['left'],$val['top'],$fontColor,$val['fontPath'],$val['text']);
            }
        }
        //生成图片
        if(!empty($filename)){
            $res = imagejpeg ($imageRes,'uploads/poster/'.$filename,90); //保存到本地
            imagedestroy($imageRes);
            if(!$res) return false;
            return $filename;
        }else{
            imagejpeg ($imageRes);     //在浏览器上显示
            imagedestroy($imageRes);
        }
    }

}